package com.lvhaosb.newpneumonia.spider;

import com.lvhaosb.newpneumonia.POJO.vo.DomesticCityEpidemicInfo;
import com.lvhaosb.newpneumonia.POJO.vo.DomesticEpidemicInfo;
import com.lvhaosb.newpneumonia.POJO.vo.ForeignEpidemicInfo;
import com.lvhaosb.newpneumonia.service.DomesticCityEpidemicService;
import com.lvhaosb.newpneumonia.service.DomesticEpidemicService;
import com.lvhaosb.newpneumonia.service.ForeignEpidemicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.Date;
import java.util.List;

@Component
public class SpiderPipeline implements Pipeline {
    @Autowired
    private DomesticEpidemicService domesticEpidemicService;
    @Autowired
    private DomesticCityEpidemicService domesticCityEpidemicService;
    @Autowired
    private ForeignEpidemicService foreignEpidemicService;

    @Override
    public void process(ResultItems resultItems, Task task) {
        //获取封装好的数据
        DomesticEpidemicInfo domesticEpidemicInfo = resultItems.get("domesticEpidemicInfo");
        List<DomesticCityEpidemicInfo> domesticCityEpidemicInfoList = resultItems.get("domesticCityEpidemicInfoList");
        List<ForeignEpidemicInfo> foreignEpidemicInfoList = resultItems.get("foreignEpidemicInfoList");

        //如果不为空，则保存到数据库
        if(domesticEpidemicInfo != null){
            domesticEpidemicService.save(domesticEpidemicInfo);
            System.out.println(new Date() + ":国内疫情数据存入数据库");
        }
        for(DomesticCityEpidemicInfo domesticCityEpidemicInfo: domesticCityEpidemicInfoList){
            domesticCityEpidemicService.save(domesticCityEpidemicInfo);
            System.out.println(new Date() + ":" + domesticCityEpidemicInfo.getCity() + "省疫情数据存入数据库");
        }
        for(ForeignEpidemicInfo foreignEpidemicInfo: foreignEpidemicInfoList){
            foreignEpidemicService.save(foreignEpidemicInfo);
            System.out.println(new Date() + ":" + foreignEpidemicInfo.getCountry() + "疫情数据存入数据库");
        }

    }
}
